import React, { Component } from "react";
import { TabPage, SearchAdvanced, RouteLayout } from "weaver-mobile-page";
import { Icon, tools, Echarts, ActivityIndicator, Result } from 'weaver-mobile';
import { toJS } from "mobx";
import { inject, observer } from "mobx-react"
import { Route, withRouter } from 'react-router-dom';
import * as Util from "../../public/util"

import DetailListComponent from "./DetailListComponent";
import MoreListComponent from "./MoreListComponent";
import NoDataComponent from "../common/NoDataComponent"

const { getLabel } = tools;


const echartOption = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
      type: 'shadow',      // 默认为直线，可选为：'line' | 'shadow'
    },
    extraCssText: "z-index:3",
    triggerOn: 'mousemove|click',
  },
  legend: {
    data: [],
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01],
    triggerEvent: true,
  },
  yAxis: {
    type: 'category',
    data: [],
    triggerEvent: true,
  },
  series: {},
  grid: {
    top: "5%",
    bottom: '3%',
    containLabel: true
  },
  axisLabel: {
    color: "#000",
    interval: 0,
    formatter: function (value) {
      if (value.length > 4) {
        return value.substring(0, 4) + "...";
      } else {
        return value;
      }
    }
  },
}

@withRouter
@inject("docReportStore")
@observer
class DocReport extends Component {

  prefixCls = 'odoc-report'


  componentDidMount() {
    const { docReportStore } = this.props;
    docReportStore.getCondition();
    docReportStore.getUserId();

  }

  componentWillUnmount() {
    const { docReportStore } = this.props;
    docReportStore.setTabKey("workflowCount")
  }

  render() {
    const tabs = [
      { title: '流程统计', key: "workflowCount" },
      { title: '公文统计', key: "docCount" },
    ]
    const { history, docReportStore } = this.props;
    const { search, detailLayout, workflowStatus, changeTab, tabKey, docEchart1, moreLayout, workflowDetailLayout, submit, docCountSearch,
      docCountSubmit, loading, hasRight } = docReportStore;
    if (!hasRight) {
      return <div className='noRightRep'><Result
        img={<Icon type="blog-private" className="spe" style={{ color: '#868686' }} size='lg' />}
        // title={getLabel("514387", "你没有访问当前页面的权限！")}
        message={getLabel("514387", "你没有访问当前页面的权限！")}
      /></div>
    }
    return (
      <div className={`${this.prefixCls}`}>

        <TabPage
          className="tab-page-example"
          btns={[
            tabKey == "workflowCount" && <Icon type="filter-o" style={{ color: "#666" }} onClick={() => history.push(search.path)} />,
            tabKey == "docCount" && <Icon type="filter-o" style={{ color: "#666" }} onClick={() => history.push(docCountSearch.path)} />,
          ]}
          span={[3, 1]}
          tabs={tabs}
          tabProps={{
            onChange: (tab) => changeTab(tab),
          }}
          defaultTabBarProps={{ page: 4 }}
        />

        <SearchAdvanced
          store={search}
          onSubmit={() => submit()}
        />

        <SearchAdvanced
          store={docCountSearch}
          onSubmit={() => docCountSubmit()}
        />
        <ActivityIndicator toast text="Loading..." animating={loading} />

        {tabKey == "workflowCount" && this.getFlowCountContent()}
        {tabKey == "docCount" && this.getDocCountContent()}

        {this.getRouteLayout(moreLayout, "more")}
        {this.getRouteLayout(detailLayout, "detail")}

      </div>
    )
  }

  getFlowCount() {
    const { docReportStore, history } = this.props
    const { flowCountData, detailLayout } = docReportStore;
    const flowCountComponent = toJS(flowCountData).map((item, index) => {
      return (
        <div
          className={`${this.prefixCls}-flowitem`}
          key={index}
          style={{ background: `${item.iconBackground}` }}
          onClick={() => this.goWorkflowList(index)}
        >
          <span>
            <span className={`${this.prefixCls}-flowitem-title`}>{item.title}&nbsp;:&nbsp;</span>
            <span className={`${this.prefixCls}-flowitem-num`}>{item.num}</span>
          </span>

          <span className={`${this.prefixCls}-flowitem-right`}>
            {
              item.isUp == "2" &&
              <span style={{ color: '#d20000' }}>
                <Icon type="play" style={{ width: "12px", transform: "rotate(90deg)", verticalAlign: "middle" }} />
                <span>{item.percent} &nbsp;</span>
              </span>
            }
            {
              item.isUp == "1" &&
              <span >
                <Icon type="play" style={{ width: "12px", transform: "rotate(-90deg)", verticalAlign: "middle" }} />
                <span>{item.percent} &nbsp;</span>
              </span>
            }
            <span>{item.suffix}</span>
          </span>
        </div>
      )
    })
    return flowCountComponent
  }

  //获取路由弹出层 
  getRouteLayout(layout, type = "more") {
    const { workflowFormData, detailData, docCountData } = this.props.docReportStore;
    const routeLayout = (
      <Route
        key={layout.id}
        path={layout.path}
        render={(props) => {
          const pathname = props.location.pathname;
          return (
            <RouteLayout>
              <div
                key="wmPoutePageDemo"
                className="wm-route-layout wm-demo-route-layout-page"
              >
                {
                  type == "detail" &&
                  <DetailListComponent
                    pathname={pathname}
                    formData={toJS(detailData)}
                    docCountData={docCountData}
                  />
                }
                {
                  type == "more" &&
                  < MoreListComponent
                    pathname={pathname}
                    formData={toJS(workflowFormData)}
                    docCountData={docCountData}
                  />
                }
              </div>
            </RouteLayout>
          )
        }}
      />
    )
    return routeLayout;
  }

  goWorkflowList(index) {
    const { docReportStore, history } = this.props;
    const { detailLayout, setDetailData } = docReportStore;
    setDetailData(index, "");
    history.push({
      pathname: detailLayout.path,
    })
  }

  //获取流程统计页面
  getFlowCountContent() {
    const { flowEchart1, flowEchart2, workflowFormData } = this.props.docReportStore;
    const showLinkEchart = workflowFormData.officaltype == "" ? false : true;
    return (
      <div className={`${this.prefixCls}-workflowEchart`}>
        <div className={`${this.prefixCls}-statistics`}>
          {this.getFlowCount()}
        </div>
        {this.getEchar(toJS(flowEchart1), "1")}

        {showLinkEchart && this.getEchar(toJS(flowEchart2), "5")}
      </div>
    )
  }

  //获取公文统计页面
  getDocCountContent() {
    const { docReportStore } = this.props;
    const { docEchart1, docEchart2, docEchart3 } = docReportStore
    return (
      <div className={`${this.prefixCls}-docCount`} style={{ height: "calc( 100% - 45px)" }}>
        {this.getEchar(toJS(docEchart1), "2")}
        {this.getEchar(toJS(docEchart2), "3")}
        {this.getEchar(toJS(docEchart3), "4")}
      </div>
    )
  }

  //获取echarts 图表
  getEchar(data, type) {
    let option = this.getEchartOption(data);
    let isWorkflow = true;
    let haveData = false;
    //type 默认是公文流程全部  2 是公文种类 3公文主题 4是月度统计 5发文环节
    if (type == "2" || type == "3") {
      option = this.getDocEchartOption(data);
      isWorkflow = false;
    } else if (type == "4") {
      option = this.getDocMountCountOption(data);
    } else if (type == "5") {
      option = this.getDocMountCountOption(data, true);
    }
    if (data.seriesData) {
      let all = 0;
      for (var i in data.seriesData) {
        all += data.seriesData[i];
      }
      if (all > 0) {
        haveData = true;
      }
    }
    if (data.endReqData && data.endReqData.length < 5) {
      haveData = false;
    }
    return (
      <div>
        <div className={`${this.prefixCls}-flowEchart`}>
          <div className={`${this.prefixCls}-flowEchart-title`}>
            <span className={`${this.prefixCls}-verticalLine`}></span>
            {data.title}
            {type == "1" && <span>(top5)</span>}
            {(type == "2" || type == "3") && <span>(top10)</span>}
          </div>
          {(type != "4" && haveData) &&
            <span className={`${this.prefixCls}-flowEchart-more`} onClick={() => this.getSearData(isWorkflow, type)}>
              {getLabel(17499, "更多")}
              <Icon type={"arrow-down-o"} className={`${this.prefixCls}-flowEchart-moreIcon`} />
            </span>
          }
        </div>
        <div style={{ width: '100%', height: '250px' }}>
          {
            ((type == "1" && data.endReqData && data.endReqData.length > 0) || haveData)
              ?
              <Echarts
                ref="chart2"
                option={option}
                useDefault={false}
                chartAction={(chart) => this.chartAction(chart)}
              />
              :
              <NoDataComponent />
          }
        </div>
      </div>
    )
  }

  //获取公文流程echarts图表option
  getEchartOption(data) {
    const option = {
      ...echartOption,
      legend: {
        data: data.legend,
      },
      yAxis: {
        type: 'category',
        data: data.yAxisData
      },
      series: data.series,
      grid: {
        top: '30px',
        containLabel: true,
      },
    }
    return option;
  }

  //获取公文种类、公文分类 echarts图表option
  getDocEchartOption(data) {
    if (!data.yAxisData) {
      return;
    }
    const option = {
      ...echartOption,
      yAxis: {
        type: 'category',
        data: data.yAxisData,
      },
      series: [
        {
          type: 'bar',
          data: data.seriesData,
          itemStyle: {
            color: "#6fbcea"
          },
          id: data.id,
          dataKey: data.dataKey,
        },
      ],
    }
    return option;
  }

  //获取月度公文echarts图表option 和 环节统计option
  getDocMountCountOption(data, isLink = false) {
    let option = {
      ...echartOption,
      xAxis: {
        data: data.xAxisData,
        axisLabel: {
          interval: 0,
          rotate: -40
        }
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, 0.01],
      },
      series: [{
        type: 'bar',
        data: data.seriesData,
        itemStyle: {
          color: "#6fbcea"
        },
        id: data.id,
        dataKey: data.dataKey,
      }],
      grid: {
        bottom: '7%',
        top: '5%',
        containLabel: true
      },
      axisLabel: {}
    };
    return option;
  }

  //echarts 图表点击事件
  chartAction(chart) {
    const { docReportStore, history } = this.props;
    const { setDetailData, detailLayout, setDocCountData } = docReportStore
    chart.on('click', params => {
      let option = chart.getModel().option;
      if (params.seriesId == "flowing" || params.seriesId == "end" || params.seriesId == "linkCount") {
        const status = option.series[params.seriesIndex].status;
        const dataKey = option.series[params.seriesIndex].dataKey[params.dataIndex];
        setDetailData(status, dataKey)
      }
      if (params.seriesId == "echart1" || params.seriesId == "echart2" || params.seriesId == "echart3") {
        const dataKey = option.series[params.seriesIndex].dataKey[params.dataIndex];
        setDocCountData(dataKey)
      }
      history.push({
        pathname: detailLayout.path,
        query: {
          seriesId: params.seriesId,
        }
      })
    });
  }

  getSearData(isWorkflow, echartType) {
    const { docReportStore, history } = this.props;
    const { detailLayout, search, setFormData, moreLayout } = docReportStore;
    const formData = Util.getFormData(toJS(search.form.formParams))
    setFormData(formData)
    history.push({
      pathname: moreLayout.path,
      query: { echartType, isWorkflow }
    })

  }






}

export default DocReport;